package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.ScriptSource;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    private final StringRedisTemplate stringRedisTemplate;
    private final String name;

    private static final String LOCK_PREFIX ="lock:";
    // 此处的前缀,代表的是虚拟机唯一标记
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";


    private static final DefaultRedisScript<Long> UNLOCK_LUA=new DefaultRedisScript<>();
    static{
        UNLOCK_LUA.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_LUA.setResultType(Long.class);
    }

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(Long ttl) {
        long threadId = Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + name, ID_PREFIX+threadId, ttl, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(success);
    }

    @Override
    public void unlock() {
        stringRedisTemplate.execute(UNLOCK_LUA, Collections.singletonList(LOCK_PREFIX + name),ID_PREFIX+Thread.currentThread().getId());
    }

    /*@Override
    public void unlock() {
        String oldId = stringRedisTemplate.opsForValue().get(LOCK_PREFIX + name);
        String currentId = ID_PREFIX + Thread.currentThread().getId();
        if(currentId.equals(oldId)){
            stringRedisTemplate.delete(LOCK_PREFIX +name);
        }
    }*/
}
